package com.example.common.util;

import com.example.common.constant.BaseConstants;
import com.example.common.entity.BaseEntity;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@UtilityClass
@Slf4j
public class ConvertUtil {

    public static <T, V extends Object> T convert(V v, Class<T> classT) {
        T t = null;
        try {
            t = classT.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        BeanUtils.copyProperties(v, t);
        return t;
    }

    public static <T, V extends Object> List<T> convert(List<V> vList, Class<T> classT) {
        return vList.stream().map(e ->
                convert(e, classT)
        ).collect(Collectors.toList());
    }

    /**
     * 初始插入
     *
     * @param baseEntity
     */
    public static void initInsertEntity(BaseEntity baseEntity) {
        baseEntity.setCreator(BaseConstants.SYSTEM);
        baseEntity.setModifier(BaseConstants.SYSTEM);
        baseEntity.setCreateTime(new Date());
        baseEntity.setUpdateTime(new Date());

        try {
            String currentUser = LoginUtil.getCurrentUser();
            if (StringUtils.isNotBlank(currentUser)) {
                baseEntity.setCreator(currentUser);
                baseEntity.setModifier(currentUser);
            }
        } catch (Exception e) {
            log.info("Failed to get system login user: {}", e.getMessage());
        }
    }

    /**
     * 初始更新
     *
     * @param baseEntity
     */
    public static void initUpdateEntity(BaseEntity baseEntity) {
        baseEntity.setModifier(BaseConstants.SYSTEM);
        baseEntity.setUpdateTime(new Date());

        try {
            String currentUser = LoginUtil.getCurrentUser();
            if (StringUtils.isNotBlank(currentUser)) {
                baseEntity.setModifier(currentUser);
            }
        } catch (Exception e) {
            log.info("Failed to get system login user: {}", e.getMessage());
        }
    }
}
